<template>
  <div class="work-order-list">
    <div class="header">
      <h2>U9生产订单浏览</h2>
      <div class="header-actions">

        <button class="kit-analysis-btn" @click="performSatelliteAnalysis" :disabled="selectedOrders.length === 0">
          <span class="btn-icon">🛰️</span>
          整星齐套分析
        </button>
        <button class="kit-analysis-btn" @click="goToKitAnalysis" :disabled="selectedOrders.length === 0">
          <span class="btn-icon">📊</span>
          工单工序齐套分析
        </button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      正在加载U9生产订单数据...
    </div>
    
    <!-- 错误状态 -->
    <div v-if="error" class="error">
      {{ error }}
    </div>
    
    <!-- 主内容区域 -->
    <div v-if="!loading && !error" class="main-content">
      <!-- 左侧：U9生产订单列表 -->
      <div class="left-panel" :class="{ narrow: isAnalysisMode }">
        <div class="order-list">
          <!-- 第一级：产品名称 -->
          <div v-for="(product, productKey) in groupedData" :key="productKey" class="level-1">
            <div class="level-header product-header">
              <span class="expand-icon" :class="{ 'rotated': expandedLevel1[productKey] }" @click="toggleLevel1(productKey)">▶</span>
              <button class="select-all-btn" @click="selectAllInProduct(productKey, product)" title="全选该产品下的所有订单">
                全选
              </button>
              <span class="header-text" @click="toggleLevel1(productKey)">{{ productKey }}</span>
              <span class="count" @click="toggleLevel1(productKey)">({{ getProductCount(product) }})</span>
            </div>
            
            <!-- 第二级：订单号+卫星名称 -->
            <div v-show="expandedLevel1[productKey]" class="level-2-container">
              <div v-for="(plans, planKey) in product" :key="planKey" class="level-2">
                <div class="order-item">
                  <input 
                    type="checkbox" 
                    :id="`order-${productKey}-${planKey}`"
                    :value="{ projectName: productKey, orderKey: planKey, orders: plans }"
                    v-model="selectedOrders"
                    class="order-checkbox"
                  />
                  <label :for="`order-${productKey}-${planKey}`" class="order-label">
                     <span class="order-title">{{ planKey }}</span>
                   </label>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧：齐套分析结果 -->
      <div class="right-panel" :class="{ wide: isAnalysisMode }">
        <div v-if="!hasAnalysisData" class="no-analysis-hint">
          <p>请选择订单并点击齐套分析按钮查看结果</p>
        </div>
        
        <div v-else-if="materialData.length > 0" class="analysis-results">
          <div class="table-header">
            <h3>齐套状态说明</h3>
            <div v-if="currentAnalysisInfo" class="analysis-info">
              <span class="info-label">当前分析：</span>
              <span class="info-content">{{ currentAnalysisInfo }}</span>
            </div>
          </div>
          
          <div class="material-table">
            <table>
              <thead>
                <tr>
                  <th>物料名称</th>
                  <th>物料编码</th>
                  <th>规格</th>
                  <th>齐套状态</th>
                  <th>齐套型号需求量</th>
                  <th>在制生产订单总需求量</th>
                  <th>总库存</th>
                </tr>
              </thead>
              <tbody>
                <template v-for="(item, index) in materialData" :key="index">
                  <!-- 主行 -->
                  <tr :class="getRowClass(item.status)">
                    <td>
                      <div class="material-cell">
                        <!-- 折叠按钮 -->
                        <button 
                          v-if="item.hasDetails" 
                          class="expand-btn" 
                          @click="toggleMaterialExpand(index)"
                          :class="{ 'expanded': item.isExpanded }"
                        >
                          ▶
                        </button>
                        <span class="material-name">{{ item.material || '-' }}</span>
                      </div>
                    </td>
                    <td>{{ item.materialCode || '-' }}</td>
                    <td>{{ item.spec || '-' }}</td>
                    <td>
                      <span 
                        v-if="item.status === '缺料'" 
                        class="shortage-status clickable" 
                        @click="toggleShortageExpand(index)"
                        :class="{ 'expanded': item.isShortageExpanded }"
                      >
                        {{ item.status }}
                        <span class="expand-arrow">{{ item.isShortageExpanded ? '▼' : '▶' }}</span>
                      </span>
                      <span 
                        v-else-if="item.status === '局部齐套'" 
                        class="partial-status clickable" 
                        @click="togglePartialExpand(index)"
                        :class="{ 'expanded': item.isPartialExpanded }"
                      >
                        {{ item.status }}
                        <span class="expand-arrow">{{ item.isPartialExpanded ? '▼' : '▶' }}</span>
                      </span>
                      <span v-else>{{ item.status }}</span>
                    </td>
                    <td class="required-col">
                      <div @mousedown="(event) => startDrag(event, event.currentTarget.parentElement)">{{ item.required || '-' }}</div>
                    </td>
                    <td class="total-required-col">
                      <div @mousedown="(event) => startDrag(event, event.currentTarget.parentElement)">{{ item.totalRequired || '-' }}</div>
                    </td>
                    <td>{{ item.totalStock || '-' }}</td>
                  </tr>
                  
                  <!-- 缺料状态的展开详细信息行 -->
                  <tr v-if="item.status === '缺料' && item.isShortageExpanded" class="detail-row">
                    <td colspan="7">
                      <div class="shortage-details">
                        <h4>缺料详细信息：</h4>
                        
                        <!-- 本次齐套型号需求 -->
                        <div class="shortage-section">
                          <h5>本次齐套型号需求：</h5>
                          <table class="detail-table">
                            <thead>
                              <tr>
                                <th>生产订单</th>
                                <th>卫星名称</th>
                                <th>需求数量</th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr v-for="(detail, detailIndex) in item.selectedOrderDetails" :key="detailIndex">
                                <td>{{ detail.orderNo }}</td>
                                <td>{{ detail.satelliteName }}</td>
                                <td>{{ detail.requiredQty }}</td>
                              </tr>
                            </tbody>
                          </table>
                        </div>
                        
                        <!-- 其他生产订单需求 -->
                        <div class="shortage-section" v-if="item.unselectedOrderDetails && item.unselectedOrderDetails.length > 0">
                          <h5>其他生产订单需求：</h5>
                          <table class="detail-table">
                            <thead>
                              <tr>
                                <th>生产订单</th>
                                <th>卫星名称</th>
                                <th>需求数量</th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr v-for="(detail, detailIndex) in item.unselectedOrderDetails" :key="detailIndex">
                                <td>{{ detail.orderNo }}</td>
                                <td>{{ detail.satelliteName }}</td>
                                <td>{{ detail.requiredQty }}</td>
                              </tr>
                            </tbody>
                          </table>
                        </div>
                      </div>
                    </td>
                  </tr>
                  
                  <!-- 局部齐套状态的展开详细信息行 -->
                  <tr v-if="item.status === '局部齐套' && item.isPartialExpanded" class="detail-row">
                    <td colspan="7">
                      <div class="partial-details">
                        <h4>其他在制生产订单详细信息：</h4>
                        <table class="detail-table">
                          <thead>
                            <tr>
                              <th>生产订单</th>
                              <th>卫星名称</th>
                              <th>需求数量</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr v-for="(detail, detailIndex) in item.partialOrderDetails" :key="detailIndex">
                              <td>{{ detail.orderNo }}</td>
                              <td>{{ detail.satelliteName }}</td>
                              <td>{{ detail.requiredQty }}</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </td>
                  </tr>
                  
                  <!-- 展开的详细信息行 -->
                  <tr v-if="item.isExpanded && item.hasDetails" class="detail-row">
                    <td colspan="7">
                      <div class="satellite-details">
                        <h4>卫星详细信息：</h4>
                        <table class="detail-table">
                          <thead>
                            <tr>
                              <th>卫星名称</th>
                              <th>实际需求量</th>
                              <th>已发料量</th>
                              <th>需求量</th>
                              <th>状态</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr v-for="(detail, detailIndex) in item.satelliteDetails" :key="detailIndex" :class="detail.isComplete ? 'complete-detail' : 'incomplete-detail'">
                              <td>{{ detail.satelliteName }}</td>
                              <td>{{ detail.actualReqQty }}</td>
                              <td>{{ detail.issuedQty }}</td>
                              <td>{{ detail.requiredQty }}</td>
                              <td>{{ detail.isComplete ? '已齐套' : '未齐套' }}</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </td>
                  </tr>
                </template>
              </tbody>
            </table>
          </div>
        </div>
        
        <div v-else class="loading-analysis">
          <p>正在加载分析数据...</p>
        </div>
      </div>
    </div>
    
    <!-- 无数据状态 -->
    <div v-if="!loading && !error && Object.keys(groupedData).length === 0" class="no-data">
      暂无U9生产订单数据
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { apiRequest, getApiBaseUrl, getApiEndpoint, getU9ProductionOrders, getU9Inventory } from '../utils/api.js'

// 路由
const router = useRouter()

// 响应式数据
const workOrders = ref([])
const loading = ref(true)
const error = ref(null)
const selectedOrders = ref([]) // 选中的订单
const expandedLevel1 = ref({}) // 一级标题展开状态
const materialData = ref([]) // 分析结果数据
const hasAnalysisData = ref(false) // 是否有分析数据
const currentAnalysisInfo = ref('') // 当前分析信息
const isAnalysisMode = ref(false)

// 可配置的API端点
const API_BASE_URL = getApiBaseUrl().replace(/\/$/, ''); // 确保没有尾部斜杠
// 使用统一的API端点配置
const API_ENDPOINT = getApiEndpoint('U9_PRODUCTION_ORDERS')

// U9生产订单数据解析函数
const parseU9Data = (content) => {
  try {
    // 尝试解析JSON
    const data = JSON.parse(content)
    console.log('成功解析U9数据文件')
    
    // 检查是否是嵌套的API响应格式
    if (typeof data === 'object' && data !== null && 'data' in data) {
      // 如果是 {"msg": "success", "code": "0", "data": [...]} 格式
      if ('msg' in data && 'code' in data) {
        console.log('检测到嵌套的API响应格式，提取内部数据')
        const innerData = data['data']
        if (Array.isArray(innerData)) {
          console.log(`成功提取工单数组，包含 ${innerData.length} 个元素`)
          return innerData
        } else {
          console.log(`提取的数据不是数组格式: ${typeof innerData}`)
          return innerData
        }
      } else {
        console.log('检测到包含data字段的对象格式')
        return data
      }
    } else if (typeof data === 'object' && data !== null && 'd' in data) {
      // 处理U9生产订单格式 {"d": {"Data": [...]}}
      console.log('检测到U9生产订单API响应格式，提取内部数据')
      const innerData = data['d']
      if (typeof innerData === 'object' && innerData !== null && 'Data' in innerData) {
        const u9Data = innerData['Data']
        if (Array.isArray(u9Data)) {
          console.log(`成功提取U9生产订单数组，包含 ${u9Data.length} 个元素`)
          return u9Data
        } else if (typeof u9Data === 'string') {
          // 处理Data字段为JSON字符串的情况
          try {
            const parsedData = JSON.parse(u9Data)
            if (Array.isArray(parsedData)) {
              console.log(`成功解析U9生产订单JSON字符串，包含 ${parsedData.length} 个元素`)
              return parsedData
            } else {
              console.log(`解析的U9数据不是数组格式: ${typeof parsedData}`)
              return parsedData
            }
          } catch (e) {
            console.error('解析U9数据JSON字符串失败:', e)
            console.error('Data内容预览:', u9Data.substring(0, 200) + '...')
            return null
          }
        } else {
          console.log(`提取的U9数据不是数组或字符串格式: ${typeof u9Data}`)
          return u9Data
        }
      } else {
        console.log('U9数据格式不符合预期')
        return innerData
      }
    } else if (Array.isArray(data)) {
      console.log(`检测到数组格式数据，包含 ${data.length} 个元素`)
      return data
    } else if (typeof data === 'object' && data !== null) {
      console.log('检测到对象格式数据')
      return data
    } else {
      console.log(`检测到其他格式数据: ${typeof data}`)
      return data
    }
  } catch (e) {
    // 尝试处理多个JSON对象的情况
    console.warn('单个JSON解析失败，尝试处理多JSON对象格式:', e)
    try {
      // 尝试按行分割，然后重新组合JSON对象
      const lines = content.trim().split('\n')
      const jsonObjects = []
      let currentJson = ""
      let braceCount = 0
      
      for (const line of lines) {
        const trimmedLine = line.trim()
        if (!trimmedLine) {
          continue
        }
        
        currentJson += trimmedLine
        
        // 计算大括号数量来判断JSON对象是否完整
        for (const char of trimmedLine) {
          if (char === '{') {
            braceCount++
          } else if (char === '}') {
            braceCount--
          }
        }
        
        // 当大括号平衡时，说明一个JSON对象完整了
        if (braceCount === 0 && currentJson) {
          try {
            const obj = JSON.parse(currentJson)
            jsonObjects.push(obj)
            console.log(`成功解析JSON对象 ${jsonObjects.length}`)
          } catch (e) {
            console.error('解析JSON对象失败:', e)
            console.error('JSON内容预览:', currentJson.substring(0, 200) + '...')
          }
          currentJson = ""
        }
      }
      
      // 处理最后一个可能未完整的JSON对象
      if (currentJson.trim()) {
        try {
          const obj = JSON.parse(currentJson)
          jsonObjects.push(obj)
          console.log(`成功解析最后一个JSON对象 ${jsonObjects.length}`)
        } catch (e) {
          console.error('解析最后一个JSON对象失败:', e)
          console.error('JSON内容预览:', currentJson.substring(0, 200) + '...')
        }
      }
      
      if (jsonObjects.length > 0) {
        console.log(`成功解析 ${jsonObjects.length} 个JSON对象`)
        // 合并所有JSON对象中的Data数组
        const mergedData = []
        for (let i = 0; i < jsonObjects.length; i++) {
          const jsonObj = jsonObjects[i]
          console.log(`处理第 ${i + 1} 个JSON对象`)
          if (typeof jsonObj === 'object' && jsonObj !== null && 'd' in jsonObj) {
            const innerData = jsonObj['d']
            if (typeof innerData === 'object' && innerData !== null && 'Data' in innerData) {
              if (Array.isArray(innerData['Data'])) {
                console.log(`第 ${i + 1} 个对象包含 ${innerData['Data'].length} 条数组数据`)
                mergedData.push(...innerData['Data'])
              } else if (typeof innerData['Data'] === 'string') {
                // 处理Data字段为JSON字符串的情况
                try {
                  const parsedData = JSON.parse(innerData['Data'])
                  if (Array.isArray(parsedData)) {
                    console.log(`第 ${i + 1} 个对象解析JSON字符串后包含 ${parsedData.length} 条数据`)
                    mergedData.push(...parsedData)
                  } else {
                    console.log(`第 ${i + 1} 个对象解析JSON字符串后为单个对象`)
                    mergedData.push(parsedData)
                  }
                } catch (e) {
                  console.error(`解析第 ${i + 1} 个JSON对象中的Data字符串失败:`, e)
                  console.error('Data内容预览:', innerData['Data'].substring(0, 100) + '...')
                  continue
                }
              } else {
                console.warn(`第 ${i + 1} 个对象的Data字段类型未知: ${typeof innerData['Data']}`)
              }
            } else {
              console.warn(`第 ${i + 1} 个对象缺少Data字段或格式不正确`)
            }
          } else if (Array.isArray(jsonObj)) {
            console.log(`第 ${i + 1} 个对象是数组，包含 ${jsonObj.length} 条数据`)
            mergedData.push(...jsonObj)
          } else if (typeof jsonObj === 'object' && jsonObj !== null) {
            console.log(`第 ${i + 1} 个对象是字典，直接添加`)
            mergedData.push(jsonObj)
          } else {
            console.warn(`第 ${i + 1} 个对象类型未知: ${typeof jsonObj}`)
          }
        }
        
        console.log(`成功合并数据，总计 ${mergedData.length} 条记录`)
        return mergedData
      } else {
        console.error('无法解析任何JSON对象')
        console.error('文件内容预览:', content.substring(0, 200) + '...')
        return null
      }
    } catch (multiJsonError) {
      console.error('多JSON对象解析也失败:', multiJsonError)
      console.error('文件内容预览:', content.substring(0, 200) + '...')
      return null
    }
  }
}

// 计算属性：按三级结构分组数据
const groupedData = computed(() => {
  const grouped = {}
  
  workOrders.value.forEach(order => {
    // 一级标题：ProjectName
    const projectName = order.ProjectName || '未知项目'
    
    // 二级标题：MODocNo + 空格 + SatelliteName
    const moDocNo = order.MODocNo || '未知订单号'
    const satelliteName = order.SatelliteName || '未知卫星'
    const level2Title = `${moDocNo} ${satelliteName}`
    
    if (!grouped[projectName]) {
      grouped[projectName] = {}
    }
    
    if (!grouped[projectName][level2Title]) {
      grouped[projectName][level2Title] = []
    }
    
    grouped[projectName][level2Title].push(order)
  })
  
  console.log('U9生产订单分组数据:', grouped)
  return grouped
})

// 方法
const loadWorkOrders = async () => {
  try {
    loading.value = true
    error.value = null
    
    console.log('正在从以下地址加载数据:', API_ENDPOINT)
    
    // 使用API工具进行请求
    const response = await apiRequest(API_ENDPOINT, {
      method: 'GET'
    })
    
    const data = await response.json()
    
    // 处理 Python API 服务器的响应格式，并在前端进行解析
    if (data && data.success && data.data) {
      // 使用解析函数处理从API获取的原始数据
      let parsedData
      if (typeof data.data === 'string') {
        // 如果data.data是字符串，直接解析
        parsedData = parseU9Data(data.data)
      } else {
        // 如果data.data已经是对象，转换为JSON字符串再解析
        parsedData = parseU9Data(JSON.stringify(data.data))
      }
      
      if (parsedData && Array.isArray(parsedData)) {
        workOrders.value = parsedData
        console.log('成功加载U9生产订单数据:', workOrders.value.length, '条记录')
      } else if (parsedData) {
        // 如果不是数组，尝试转换
        const dataArray = Array.isArray(parsedData) ? parsedData : [parsedData]
        workOrders.value = dataArray
        console.log('成功加载U9生产订单数据:', workOrders.value.length, '条记录')
      } else {
        throw new Error('解析U9生产订单数据失败')
      }
    } else {
      // 处理其他格式或错误
      const errorMsg = data?.message || '数据格式错误'
      throw new Error(errorMsg)
    }
    
  } catch (err) {
    console.error('加载U9生产订单数据失败:', err)
    error.value = `加载U9生产订单数据失败: ${err.message}`
  } finally {
    loading.value = false
  }
}



// 切换一级标题展开状态
const toggleLevel1 = (productKey) => {
  expandedLevel1.value[productKey] = !expandedLevel1.value[productKey]
}

// 全选/取消全选指定产品下的所有订单
const selectAllInProduct = (productKey, product) => {
  // 获取该产品下的所有订单
  const productOrders = []
  Object.entries(product).forEach(([planKey, plans]) => {
    productOrders.push({
      projectName: productKey,
      orderKey: planKey,
      orders: plans
    })
  })
  
  // 检查是否所有订单都已选中
  const allSelected = productOrders.every(order => 
    selectedOrders.value.some(selected => 
      selected.projectName === order.projectName && selected.orderKey === order.orderKey
    )
  )
  
  if (allSelected) {
    // 如果全部已选中，则取消选中该产品下的所有订单
    selectedOrders.value = selectedOrders.value.filter(selected => 
      !(selected.projectName === productKey)
    )
  } else {
    // 如果未全部选中，则选中该产品下的所有订单
    // 先移除该产品下已选中的订单，避免重复
    selectedOrders.value = selectedOrders.value.filter(selected => 
      !(selected.projectName === productKey)
    )
    // 然后添加该产品下的所有订单
    selectedOrders.value.push(...productOrders)
  }
}

// 拖拽功能
const startDrag = (event, element) => {
  event.preventDefault()
  
  const startX = event.clientX
  const scrollLeft = element.scrollLeft
  
  element.classList.add('dragging')
  
  const handleMouseMove = (e) => {
    const x = e.clientX - startX
    element.scrollLeft = scrollLeft - x
  }
  
  const handleMouseUp = () => {
    element.classList.remove('dragging')
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  }
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

// 整星齐套分析
const performSatelliteAnalysis = async () => {
  if (selectedOrders.value.length === 0) {
    alert('请先选择要分析的订单')
    return
  }
  
  console.log('执行整星齐套分析:', selectedOrders.value)
  
  // 设置分析模式，调整面板宽度
  isAnalysisMode.value = true
  
  // 根据选中的订单提取物料数据
  const materialMap = new Map()
  
  selectedOrders.value.forEach(selectedOrder => {
    const { projectName, orderKey, orders } = selectedOrder
    
    // 遍历该订单组下的所有工单
    orders.forEach(order => {
      if (order.PickList && Array.isArray(order.PickList)) {
        order.PickList.forEach(item => {
          // 使用物料编码作为唯一键，相同编码的物料进行汇总
          const materialKey = item.ItemCode || ''
          
          if (materialMap.has(materialKey)) {
            // 如果物料已存在，累加ActualReqQty和IssuedQty
            const existing = materialMap.get(materialKey)
            existing.actualReqQty += (item.ActualReqQty || 0)
            existing.issuedQty += (item.IssuedQty || 0)
            existing.requiredQty = existing.actualReqQty - existing.issuedQty
          } else {
            // 新物料
            const actualReqQty = item.ActualReqQty || 0
            const issuedQty = item.IssuedQty || 0
            materialMap.set(materialKey, {
              material: item.ItemName || '',
              materialCode: item.ItemCode || '',
              spec: item.ItemSpec || '',
              actualReqQty: actualReqQty,
              issuedQty: issuedQty,
              requiredQty: actualReqQty - issuedQty
            })
          }
        })
      }
    })
  })
  
  // 统计未勾选订单中相同物料的总需求量
  const unselectedMaterialTotalMap = new Map()
  
  // 构建已勾选订单的集合，用于快速查找
  const selectedOrderKeys = new Set()
  selectedOrders.value.forEach(selectedOrder => {
    selectedOrderKeys.add(selectedOrder.orderKey)
  })
  
  // 遍历所有订单数据，只统计未勾选的订单
  Object.values(groupedData.value).forEach(product => {
    Object.entries(product).forEach(([orderKey, orders]) => {
      // 只处理未勾选的订单
      if (!selectedOrderKeys.has(orderKey)) {
        orders.forEach(order => {
          if (order.PickList && Array.isArray(order.PickList)) {
            order.PickList.forEach(item => {
              const materialKey = item.ItemCode || ''
              if (materialKey.trim() !== '') {
                const actualReqQty = item.ActualReqQty || 0
                
                if (unselectedMaterialTotalMap.has(materialKey)) {
                  unselectedMaterialTotalMap.set(materialKey, unselectedMaterialTotalMap.get(materialKey) + actualReqQty)
                } else {
                  unselectedMaterialTotalMap.set(materialKey, actualReqQty)
                }
              }
            })
          }
        })
      }
    })
  })
  
  console.log('未勾选订单物料总需求量统计:', unselectedMaterialTotalMap)
  
  // 提取所有物料编码用于查询U9库存
  const materialCodes = Array.from(materialMap.keys()).filter(code => code.trim() !== '')
  
  try {
     // 查询U9库存数据
     console.log('查询U9库存，物料编码:', materialCodes)
     const u9InventoryData = await getU9Inventory(materialCodes)
     console.log('U9库存查询结果:', u9InventoryData)
     
     // U9响应数据解析函数（参考KitAnalysis.vue的实现）
     const parseResponseData = (responseData) => {
       if (!responseData) return []
     
       let dataArray = []
     
       try {
         // 检查Data字段是否为字符串（需要解析）还是已经是对象
         if (responseData.Data && typeof responseData.Data === 'string') {
           dataArray = JSON.parse(responseData.Data)
         } else if (responseData.Data && Array.isArray(responseData.Data)) {
           dataArray = responseData.Data
         } else if (Array.isArray(responseData)) {
           dataArray = responseData
         } else if (responseData.d && responseData.d.Data) {
           if (typeof responseData.d.Data === 'string') {
             dataArray = JSON.parse(responseData.d.Data)
           } else {
             dataArray = responseData.d.Data
           }
         }
     
         // 确保 dataArray 是数组
         if (!Array.isArray(dataArray)) {
           return []
         }
     
         return dataArray
       } catch (error) {
         console.warn('解析U9响应数据失败:', error)
         return []
       }
     }
     
     // 解析U9库存数据并建立映射
     const u9StockMap = new Map()
     
     if (u9InventoryData && Array.isArray(u9InventoryData)) {
       u9InventoryData.forEach((item, index) => {
         console.log(`处理U9库存数据项 ${index}:`, item)
         
         // 使用统一的解析函数解析U9响应数据
         const dataArray = parseResponseData(item)
         console.log(`解析后的数据数组长度: ${dataArray.length}, 内容:`, dataArray)
         
         if (dataArray.length > 0) {
           // 遍历数组中的每个对象，累加StoreQty
           dataArray.forEach((stockItem, stockIndex) => {
             console.log(`库存项 ${stockIndex} 详细信息:`, stockItem)
             if (stockItem && typeof stockItem === 'object' && stockItem.ItemCode) {
               const itemCode = stockItem.ItemCode
               const storeQty = parseFloat(stockItem.StoreQty) || 0
               
               console.log(`物料 ${itemCode} 单条库存: ${storeQty} (批次: ${stockItem.LotCode || '无'}, 仓库: ${stockItem.WhName || '无'})`)
               
               if (u9StockMap.has(itemCode)) {
                 const oldQty = u9StockMap.get(itemCode)
                 const newQty = oldQty + storeQty
                 u9StockMap.set(itemCode, newQty)
                 console.log(`物料 ${itemCode} 累加库存: ${oldQty} + ${storeQty} = ${newQty}`)
               } else {
                 u9StockMap.set(itemCode, storeQty)
                 console.log(`物料 ${itemCode} 初始库存: ${storeQty}`)
               }
             }
           })
         }
       })
     }
     
     console.log('最终库存映射:', u9StockMap)
     
     // 转换为数组格式并添加库存信息，同时进行齐套状态分析
     materialData.value = Array.from(materialMap.values()).map(item => {
       const u9Stock = u9StockMap.get(item.materialCode) || 0
       console.log(`物料 ${item.materialCode} 最终库存: ${u9Stock}`)
       
       // 获取该物料在未勾选订单中的总需求量
       const totalRequiredFromUnselected = unselectedMaterialTotalMap.get(item.materialCode) || 0
       
       // 齐套状态判断逻辑（基于库存和需求量的关系）
       let status = '待分析'
       let satelliteDetails = []
       let hasCompleteItems = false
       
       const selectedRequiredQty = item.requiredQty // 齐套型号需求量（选中订单的需求量）
       const unselectedRequiredQty = totalRequiredFromUnselected // 在制生产订单总需求量（未勾选订单的需求量）
       const totalStock = u9Stock // 总库存
       
       // 根据用户定义的逻辑判断齐套状态
       if (selectedRequiredQty > totalStock) {
         // 如果齐套型号需求量 > 总库存，说明为缺料状态
         status = '缺料'
       } else if (selectedRequiredQty + unselectedRequiredQty > totalStock) {
         // 如果齐套型号需求量 + 在制生产订单总需求量 > 总库存，但齐套型号需求量 < 总库存，说明是局部齐套
         status = '局部齐套'
       } else {
         // 如果齐套型号需求量 + 在制生产订单总需求量 <= 总库存，说明全部齐套
         status = '全部齐套'
       }
       
       // 如果累计的ActualReqQty和IssuedQty不相等，且存在单独相等的项目，收集卫星详细信息
       if (item.actualReqQty !== item.issuedQty) {
         const completeItems = []
         const incompleteItems = []
         
         // 遍历该物料在各个订单中的详细信息
         selectedOrders.value.forEach(selectedOrder => {
           selectedOrder.orders.forEach(order => {
             if (order.PickList && Array.isArray(order.PickList)) {
               order.PickList.forEach(pickItem => {
                 if (pickItem.ItemCode === item.materialCode) {
                   const actualReq = pickItem.ActualReqQty || 0
                   const issued = pickItem.IssuedQty || 0
                   
                   const satelliteInfo = {
                     satelliteName: order.SatelliteName || '未知卫星',
                     actualReqQty: actualReq,
                     issuedQty: issued,
                     requiredQty: actualReq - issued,
                     isComplete: actualReq === issued
                   }
                   
                   if (satelliteInfo.isComplete) {
                     completeItems.push(satelliteInfo)
                     hasCompleteItems = true
                   } else {
                     incompleteItems.push(satelliteInfo)
                   }
                 }
               })
             }
           })
         })
         
         // 只有当累计不相等且存在单独相等的项目时才显示详细信息
       if (hasCompleteItems) {
         satelliteDetails = [...completeItems, ...incompleteItems]
       }
     }
     
     // 收集缺料详细信息（用于缺料状态展开显示）
     let shortageDetails = {
       selectedOrders: [], // 本次齐套型号需求
       unselectedOrders: [] // 其他生产订单需求
     }
     
     if (status === '缺料') {
       // 收集本次齐套型号各个生产订单需求数量
       selectedOrders.value.forEach(selectedOrder => {
         selectedOrder.orders.forEach(order => {
           if (order.PickList && Array.isArray(order.PickList)) {
             order.PickList.forEach(pickItem => {
               if (pickItem.ItemCode === item.materialCode) {
                 const actualReq = pickItem.ActualReqQty || 0
                 if (actualReq > 0) {
                   shortageDetails.selectedOrders.push({
                     orderNo: order.MODocNo || '未知订单',
                     satelliteName: order.SatelliteName || '未知卫星',
                     requiredQty: actualReq
                   })
                 }
               }
             })
           }
         })
       })
       
       // 收集其他生产订单所需数量（未勾选的订单）
       const selectedOrderKeys = new Set()
       selectedOrders.value.forEach(selectedOrder => {
         selectedOrderKeys.add(selectedOrder.orderKey)
       })
       
       Object.values(groupedData.value).forEach(product => {
         Object.entries(product).forEach(([orderKey, orders]) => {
           if (!selectedOrderKeys.has(orderKey)) {
             orders.forEach(order => {
               if (order.PickList && Array.isArray(order.PickList)) {
                 order.PickList.forEach(pickItem => {
                   if (pickItem.ItemCode === item.materialCode) {
                     const actualReq = pickItem.ActualReqQty || 0
                     if (actualReq > 0) {
                       shortageDetails.unselectedOrders.push({
                         orderNo: order.MODocNo || '未知订单',
                         satelliteName: order.SatelliteName || '未知卫星',
                         requiredQty: actualReq
                       })
                     }
                   }
                 })
               }
             })
           }
         })
       })
     }
      
      // 收集局部齐套详细信息（用于局部齐套状态展开显示）
       let partialOrderDetails = []
       if (status === '局部齐套') {
         // 收集其他生产订单所需数量（未勾选的订单）
         const selectedOrderKeys = new Set()
         selectedOrders.value.forEach(selectedOrder => {
           selectedOrderKeys.add(selectedOrder.orderKey)
         })
         
         Object.values(groupedData.value).forEach(product => {
           Object.entries(product).forEach(([orderKey, orders]) => {
             if (!selectedOrderKeys.has(orderKey)) {
               orders.forEach(order => {
                 if (order.PickList && Array.isArray(order.PickList)) {
                   order.PickList.forEach(pickItem => {
                     if (pickItem.ItemCode === item.materialCode) {
                       const actualReq = pickItem.ActualReqQty || 0
                       if (actualReq > 0) {
                         partialOrderDetails.push({
                           orderNo: order.MODocNo || '未知订单',
                           satelliteName: order.SatelliteName || '未知卫星',
                           requiredQty: actualReq
                         })
                       }
                     }
                   })
                 }
               })
             }
           })
         })
       }
       
       return {
         material: item.material,
         materialCode: item.materialCode,
         spec: item.spec,
         status: status,
         required: item.requiredQty, // ActualReqQty - IssuedQty
         totalRequired: totalRequiredFromUnselected, // 在制生产订单总需求量（未勾选订单）
         totalStock: u9Stock,
         satelliteDetails: satelliteDetails, // 卫星详细信息
         hasDetails: hasCompleteItems && satelliteDetails.length > 0, // 只有当累计不相等且存在单独相等的项目时才显示详细信息
         isExpanded: false, // 折叠状态
         selectedOrderDetails: shortageDetails.selectedOrders, // 本次齐套型号需求详细信息
         unselectedOrderDetails: shortageDetails.unselectedOrders, // 其他生产订单需求详细信息
         isShortageExpanded: false, // 缺料展开状态
         partialOrderDetails: partialOrderDetails, // 局部齐套详细信息
         isPartialExpanded: false // 局部齐套展开状态
       }
     })
     
     // 按照齐套状态排序：缺料 > 局部齐套 > 全部齐套
     materialData.value.sort((a, b) => {
       const statusPriority = {
         '缺料': 1,
         '局部齐套': 2,
         '全部齐套': 3
       }
       
       const priorityA = statusPriority[a.status] || 999
       const priorityB = statusPriority[b.status] || 999
       
       if (priorityA !== priorityB) {
         return priorityA - priorityB
       }
       
       // 如果状态相同，按物料编码排序
       return a.materialCode.localeCompare(b.materialCode)
     })
    
  } catch (error) {
    console.error('查询U9库存数据失败:', error)
    
    // 如果查询失败，仍然显示物料数据，但库存为0
    materialData.value = Array.from(materialMap.values()).map(item => {
      // 获取该物料在未勾选订单中的总需求量
       const totalRequiredFromUnselected = unselectedMaterialTotalMap.get(item.materialCode) || 0
      
      // 收集缺料详细信息（用于缺料状态展开显示）
      let shortageDetails = {
        selectedOrders: [], // 本次齐套型号需求
        unselectedOrders: [] // 其他生产订单需求
      }
      
      // 收集本次齐套型号各个生产订单需求数量
      selectedOrders.value.forEach(selectedOrder => {
        selectedOrder.orders.forEach(order => {
          if (order.PickList && Array.isArray(order.PickList)) {
            order.PickList.forEach(pickItem => {
              if (pickItem.ItemCode === item.materialCode) {
                const actualReq = pickItem.ActualReqQty || 0
                if (actualReq > 0) {
                  shortageDetails.selectedOrders.push({
                    orderNo: order.MODocNo || '未知订单',
                    satelliteName: order.SatelliteName || '未知卫星',
                    requiredQty: actualReq
                  })
                }
              }
            })
          }
        })
      })
      
      // 收集其他生产订单所需数量（未勾选的订单）
      const selectedOrderKeys = new Set()
      selectedOrders.value.forEach(selectedOrder => {
        selectedOrderKeys.add(selectedOrder.orderKey)
      })
      
      Object.values(groupedData.value).forEach(product => {
        Object.entries(product).forEach(([orderKey, orders]) => {
          if (!selectedOrderKeys.has(orderKey)) {
            orders.forEach(order => {
              if (order.PickList && Array.isArray(order.PickList)) {
                order.PickList.forEach(pickItem => {
                  if (pickItem.ItemCode === item.materialCode) {
                    const actualReq = pickItem.ActualReqQty || 0
                    if (actualReq > 0) {
                      shortageDetails.unselectedOrders.push({
                        orderNo: order.MODocNo || '未知订单',
                        satelliteName: order.SatelliteName || '未知卫星',
                        requiredQty: actualReq
                      })
                    }
                  }
                })
              }
            })
          }
        })
      })
      
      return {
          material: item.material,
          materialCode: item.materialCode,
          spec: item.spec,
          status: '库存查询失败',
          required: item.requiredQty,
          totalRequired: totalRequiredFromUnselected, // 在制生产订单总需求量（未勾选订单）
          totalStock: 0,
          selectedOrderDetails: shortageDetails.selectedOrders, // 本次齐套型号需求详细信息
          unselectedOrderDetails: shortageDetails.unselectedOrders, // 其他生产订单需求详细信息
          isShortageExpanded: false, // 缺料展开状态
          partialOrderDetails: shortageDetails.unselectedOrders, // 局部齐套详细信息（使用未选中订单数据）
          isPartialExpanded: false // 局部齐套展开状态
        }
    })
    
    // 按照齐套状态排序：缺料 > 局部齐套 > 全部齐套
    materialData.value.sort((a, b) => {
      const statusPriority = {
        '缺料': 1,
        '局部齐套': 2,
        '全部齐套': 3
      }
      
      const priorityA = statusPriority[a.status] || 999
      const priorityB = statusPriority[b.status] || 999
      
      if (priorityA !== priorityB) {
        return priorityA - priorityB
      }
      
      // 如果状态相同，按物料编码排序
      return a.materialCode.localeCompare(b.materialCode)
    })
  }
  
  hasAnalysisData.value = true
  currentAnalysisInfo.value = `已选择 ${selectedOrders.value.length} 个订单进行整星齐套分析，共分析 ${materialData.value.length} 种物料`
}

// 切换物料详细信息展开状态
const toggleMaterialExpand = (index) => {
  if (materialData.value[index]) {
    materialData.value[index].isExpanded = !materialData.value[index].isExpanded
  }
}

// 切换缺料状态展开
const toggleShortageExpand = (index) => {
  if (materialData.value[index]) {
    materialData.value[index].isShortageExpanded = !materialData.value[index].isShortageExpanded
  }
}

// 切换局部齐套状态展开
const togglePartialExpand = (index) => {
  if (materialData.value[index]) {
    materialData.value[index].isPartialExpanded = !materialData.value[index].isPartialExpanded
  }
}

// 获取表格行样式类名
const getRowClass = (status) => {
  switch (status) {
    case '全部齐套':
      return 'status-complete'
    case '局部齐套':
      return 'status-partial'
    case '缺料':
      return 'status-shortage'
    default:
      return ''
  }
}

// 获取产品下的工单总数
const getProductCount = (product) => {
  let count = 0
  Object.values(product).forEach(plans => {
    count += plans.length
  })
  return count
}

// 跳转到齐套分析页面
const goToKitAnalysis = () => {
  // 如果有选中的订单，传递所有选中订单的MODocNo
  if (selectedOrders.value.length > 0) {
    const moDocNos = selectedOrders.value.map(order => {
      // 从orderKey中提取MODocNo（orderKey格式为"MODocNo SatelliteName"）
      const orderKey = order.orderKey
      const spaceIndex = orderKey.indexOf(' ')
      return spaceIndex !== -1 ? orderKey.substring(0, spaceIndex) : orderKey
    })
    
    router.push({
      path: '/kit-analysis',
      query: { moDocNos: moDocNos.join(',') }
    })
  } else {
    router.push('/kit-analysis')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  loadWorkOrders()
})
</script>

<style scoped>
.work-order-list {
  padding: 0;
  width: 100%;
  max-width: none;
  margin: 0;
  background: #f8f9fa;
  min-height: 100vh;
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: flex;
  flex-direction: column;
}

/* Webkit浏览器滚动条样式 */
.work-order-list::-webkit-scrollbar {
  width: 8px;
}

.work-order-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.work-order-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.work-order-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.header {
  background: #ffffff;
  border-bottom: 1px solid #e9ecef;
  padding: 20px 24px;
  flex-shrink: 0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

h2 {
  color: #495057;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.refresh-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.refresh-btn:not(:disabled):hover {
  background: #5a6268;
  transform: translateY(-1px);
}

.kit-analysis-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.kit-analysis-btn:hover {
  background: #0056b3;
  transform: translateY(-1px);
}

.btn-icon {
  font-size: 16px;
}

.loading, .error, .no-data {
  text-align: center;
  padding: 60px 30px;
  font-size: 16px;
  background: #ffffff;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  margin: 20px;
}

.error {
  color: #dc3545;
  background: #f8d7da;
  border-color: #f5c6cb;
}

.loading {
  color: #6c757d;
}

.no-data {
  color: #6c757d;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧面板 */
.left-panel {
  width: 50%;
  border-right: 1px solid #e9ecef;
  background: #ffffff;
  overflow-y: auto;
  transition: width 0.3s ease;
}

.left-panel.narrow {
  width: 30%;
}

/* 右侧面板 */
.right-panel {
  width: 50%;
  background: #ffffff;
  overflow-y: auto;
  padding: 20px;
  transition: width 0.3s ease;
}

.right-panel.wide {
  width: 70%;
}

/* 列表容器 */
.order-list {
  padding: 20px;
}

/* 分级样式 */
.level-1 {
  border: 1px solid #dee2e6;
  border-radius: 8px;
  margin-bottom: 12px;
  background: #ffffff;
  overflow: hidden;
  transition: all 0.2s ease;
}

.level-1:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.level-2 {
  border-left: 3px solid #adb5bd;
  margin: 8px 0;
  background: #f8f9fa;
  border-radius: 6px;
  overflow: hidden;
}

.level-3 {
  margin: 6px 0;
}

/* 标题样式 */
.level-header {
  padding: 14px 18px;
  cursor: pointer;
  user-select: none;
  display: flex;
  align-items: center;
  transition: all 0.2s ease;
}

.level-header:hover {
  background: #f8f9fa;
}

.product-header {
  background: #495057;
  color: white;
  font-weight: 600;
  font-size: 16px;
  cursor: pointer;
}

.product-header:hover {
  background: #343a40;
}

.product-header.expanded {
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

/* 展开图标 */
.expand-icon {
  margin-right: 10px;
  font-size: 12px;
  transition: transform 0.2s ease;
  width: 16px;
  text-align: center;
  display: inline-block;
}

.expand-icon.rotated {
  transform: rotate(90deg);
}

/* 全选按钮样式 */
.select-all-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  margin-right: 10px;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.select-all-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
}

.select-all-btn:active {
  transform: translateY(0);
}

.plan-header {
  background: #e9ecef;
  color: #495057;
  font-weight: 500;
  font-size: 14px;
  border-bottom: 1px solid #dee2e6;
}

.plan-header:hover {
  background: #dee2e6;
}



.header-text {
  flex: 1;
  font-weight: inherit;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.header-text::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

.count {
  font-size: 12px;
  opacity: 0.8;
  margin-left: 10px;
  background: rgba(255, 255, 255, 0.2);
  padding: 3px 8px;
  border-radius: 12px;
  font-weight: 500;
}

/* 容器样式 */
.level-2-container {
  padding: 10px 16px;
  background: #ffffff;
}

.level-3-container {
  padding: 8px 16px;
  background: #ffffff;
  border-radius: 6px;
  margin: 4px 0;
}

/* 订单项样式 */
.order-item {
  background: #ffffff;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 8px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-item:hover {
  background: #f8f9fa;
  border-color: #adb5bd;
  transform: translateY(-1px);
}

/* 复选框样式 */
.order-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #007bff;
}

/* 标签样式 */
.order-label {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  font-size: 14px;
}

.order-title {
  font-weight: 500;
  color: #495057;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.order-title::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

.order-count {
    font-size: 12px;
    color: #6c757d;
    background: #e9ecef;
    padding: 2px 8px;
    border-radius: 12px;
  }
  
  /* 右侧分析结果样式 */
  .no-analysis-hint {
    text-align: center;
    padding: 60px 20px;
    color: #6c757d;
    font-size: 16px;
  }
  
  .analysis-results {
    background: #ffffff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .table-header {
    background: #f8f9fa;
    padding: 16px 20px;
    border-bottom: 1px solid #e9ecef;
  }
  
  .table-header h3 {
    margin: 0 0 8px 0;
    color: #495057;
    font-size: 18px;
    font-weight: 600;
  }
  
  .analysis-info {
    font-size: 14px;
    color: #6c757d;
  }
  
  .info-label {
    font-weight: 500;
  }
  
  .info-content {
    color: #495057;
  }
  
  .material-table {
    overflow-x: auto;
  }
  
  .material-table table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  table-layout: fixed;
}

.material-table th,
.material-table td {
  padding: 8px 12px;
  text-align: center;
  border: 1px solid #dee2e6;
  vertical-align: middle;
  white-space: nowrap;
  overflow: hidden;
  position: relative;
  height: 45px;
}

.material-table th:nth-child(1),
.material-table td:nth-child(1) {
  width: 15%;
}

.material-table th:nth-child(2),
.material-table td:nth-child(2) {
  width: 18%;
}

.material-table th:nth-child(3),
.material-table td:nth-child(3) {
  width: 20%;
}

.material-table th:nth-child(4),
.material-table td:nth-child(4) {
  width: 15%;
}

.material-table th:nth-child(5),
.material-table td:nth-child(5) {
  width: 16%;
}

.material-table th:nth-child(6),
.material-table td:nth-child(6) {
  width: 22%;
}

.material-table th:nth-child(7),
.material-table td:nth-child(7) {
  width: 11%;
}

.material-table th {
  background: #4472c4;
  color: white;
  font-weight: 600;
  font-size: 13px;
}

.material-table td {
  font-size: 13px;
  cursor: pointer;
}

.material-table td:hover {
  overflow-x: auto;
  white-space: nowrap;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.material-table td:hover::-webkit-scrollbar {
  display: none;
}

.material-table tbody tr:nth-child(even) {
  background: #f8f9fa;
}

/* 状态行样式 */
.status-complete {
  background: #d4edda !important;
}

.status-partial {
  background: #fff3cd !important;
}

.status-shortage {
  background: #f8d7da !important;
}
  
  .loading-analysis {
    text-align: center;
    padding: 40px 20px;
    color: #6c757d;
    font-size: 16px;
  }

/* 响应式设计 */
@media (max-width: 768px) {
  .header-section {
    padding: 16px 20px;
  }
  
  h2 {
    font-size: 20px;
    margin-bottom: 12px;
  }
  
  .kit-analysis-btn, .refresh-btn {
    padding: 8px 16px;
    font-size: 13px;
  }
  
  .btn-icon {
    font-size: 14px;
  }
  
  .order-list {
    padding: 16px;
  }
  
  .level-header {
    padding: 12px 14px;
  }
  
  .product-header {
    font-size: 15px;
  }
  
  .plan-header {
    font-size: 13px;
  }
  
  .level-2-container, .level-3-container {
    padding: 8px 12px;
  }
  
  .order-item {
    padding: 10px 12px;
    margin-bottom: 4px;
  }
  
  .order-number {
    font-size: 13px;
  }
  
  .order-spec {
    font-size: 11px;
    padding: 3px 6px;
  }
  
  .count {
    font-size: 11px;
    padding: 2px 6px;
  }
}

@media (max-width: 480px) {
  .header-section {
    padding: 12px 16px;
  }
  
  h2 {
    font-size: 18px;
  }
  
  .action-section {
    flex-direction: column;
    gap: 8px;
  }
  
  .kit-analysis-btn, .refresh-btn {
    width: 100%;
    justify-content: center;
  }
  
  .order-list {
    padding: 12px;
  }
  
  .level-header {
    padding: 10px 12px;
  }
  
  .order-item {
    padding: 8px 10px;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}

/* 物料单元格样式 */
.material-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.expand-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 12px;
  color: #666;
  padding: 2px 4px;
  border-radius: 3px;
  transition: all 0.2s ease;
  transform: rotate(0deg);
  min-width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.expand-btn:hover {
  background: #f0f0f0;
  color: #333;
}

.expand-btn.expanded {
  transform: rotate(90deg);
  color: #007bff;
}

.material-name {
  flex: 1;
}

/* 详细信息行样式 */
.detail-row {
  background: #f8f9fa !important;
}

.detail-row:hover {
  background: #f8f9fa !important;
}

.satellite-details {
  padding: 15px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  background: white;
  margin: 5px 0;
}

.satellite-details h4 {
  margin: 0 0 15px 0;
  color: #495057;
  font-size: 16px;
  font-weight: 600;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}

.detail-table th,
.detail-table td {
  padding: 8px 12px;
  text-align: left;
  border-bottom: 1px solid #dee2e6;
}

.detail-table th {
  background: #f1f3f4;
  font-weight: 600;
  color: #495057;
}

.complete-detail {
  background-color: #d4edda;
}

.incomplete-detail {
  background-color: #f8d7da;
}

/* 更新状态行样式 */
.status-complete {
  background-color: #d4edda !important;
}

.status-partial {
  background-color: #fff3cd !important;
}

.status-shortage {
  background-color: #f8d7da !important;
}

/* 缺料状态和局部齐套状态的点击样式 */
.shortage-status.clickable,
.partial-status.clickable {
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.shortage-status.clickable:hover,
.partial-status.clickable:hover {
  background-color: rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
}

.expand-arrow {
  font-size: 10px;
  transition: transform 0.2s ease;
}

.shortage-details,
.partial-details {
  padding: 15px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  background: white;
  margin: 5px 0;
}

.shortage-details h4,
.partial-details h4 {
  margin: 0 0 15px 0;
  color: #495057;
  font-size: 16px;
  font-weight: 600;
}

.shortage-section {
  margin-bottom: 20px;
}

.shortage-section:last-child {
  margin-bottom: 0;
}

.shortage-section h5 {
  margin: 0 0 10px 0;
  color: #6c757d;
  font-size: 14px;
  font-weight: 600;
}

/* 齐套型号需求量和在制生产订单总需求量列样式 */
.required-col,
.total-required-col {
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  text-overflow: unset;
  cursor: grab;
  position: relative;
}

.required-col::-webkit-scrollbar,
.total-required-col::-webkit-scrollbar {
  height: 4px;
}

.required-col::-webkit-scrollbar-track,
.total-required-col::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.required-col::-webkit-scrollbar-thumb,
.total-required-col::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.required-col::-webkit-scrollbar-thumb:hover,
.total-required-col::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.required-col:active,
.total-required-col:active {
  cursor: grabbing;
}

.required-col:hover,
.total-required-col:hover {
  background-color: rgba(108, 117, 125, 0.05);
}

.required-col div,
.total-required-col div {
  display: inline-block;
  min-width: 100%;
  padding: 0 2px;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.required-col.dragging,
.total-required-col.dragging {
  cursor: grabbing !important;
  background-color: rgba(108, 117, 125, 0.1);
}

.required-col:active div,
.total-required-col:active div {
  pointer-events: none;
}
</style>
